package com.eco.fanliapp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.SyBlacklistMapper;
import com.eco.fanliapp.entity.Administrator;
import com.eco.fanliapp.entity.AppUser;
import com.eco.fanliapp.entity.SyBlacklist;
import com.eco.fanliapp.entity.SysLog;
import com.eco.fanliapp.service.IAdministratorService;
import com.eco.fanliapp.service.IAppUserService;
import com.eco.fanliapp.service.ISyBlacklistService;
import com.eco.fanliapp.service.SysLogCommon;
import com.eco.fanliapp.vo.UserVO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户黑名单表 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-09-09
 */
@Service
public class SyBlacklistServiceImpl extends ServiceImpl<SyBlacklistMapper, SyBlacklist> implements ISyBlacklistService {

    @Autowired
    private IAppUserService iAppUserService;

    @Autowired
    private SyBlacklistMapper syBlacklistMapper;

    @Autowired
    private SysLogCommon sysLogCommon;
    @Autowired
    private IAdministratorService administratorService;
    @Autowired
    private ISyBlacklistService syBlacklistService;

    @Override
//    @Transactional
    public ServerResponse addSyBlacklist(SyBlacklist syBlacklist) {
        Integer blackScope = syBlacklist.getBlackScope();//1自己 2下级3 自己和下级
        Long userId = syBlacklist.getUserId();
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(blackScope)) {
            return ServerResponse.createByErrorMessage("用户id/黑名单范围不能为空");
        }
        AppUser user = iAppUserService.selectAppUserByUserId(userId);
        if(StringUtils.isEmpty(user)){
            return ServerResponse.createBySuccessMessage("用户不存在");
        }
        //自己
        if(blackScope == 1){
            //查询是否加入过黑名单
            SyBlacklist oneSyBlacklist = getOneSyBlacklist(user.getUserId());
            if(StringUtils.isEmpty(oneSyBlacklist)){
                //没有加入过添加黑名单
                syBlacklist.setMeInviteCode(user.getMeInviteCode());
                syBlacklist.setSuperInviteCode(user.getSuperInviteCode());
                boolean save = this.save(syBlacklist);
                if(save)return ServerResponse.createBySuccessMessage("操作成功");
            }
            if(oneSyBlacklist.getBlackScope() == 1){
                return ServerResponse.createBySuccessMessage("操作成功");
            }
            syBlacklist.setTableId(oneSyBlacklist.getTableId());
            syBlacklist.setUpdateTime(new Date());
            boolean b = this.updateById(syBlacklist);
            if(b && updateOne(user,0,null))return ServerResponse.createBySuccessMessage("操作成功");
        }

        //下级
        if(blackScope == 2){
            //查询是否加入过黑名单
            SyBlacklist oneSyBlacklist = getOneSyBlacklist(user.getUserId());
            if(StringUtils.isEmpty(oneSyBlacklist)){
                if(addSubUser(user,syBlacklist))return ServerResponse.createBySuccessMessage("操作成功");
            }
            if(oneSyBlacklist.getBlackScope() == 2){
                return ServerResponse.createBySuccessMessage("操作成功");
            }
            if(oneSyBlacklist.getBlackScope() == 1){
                boolean b = updateOne(user, 0, 2);
            }
        }
        return ServerResponse.createByErrorMessage("操作失败");
    }

    @Override
    public boolean userCheck(Long userId,String superInviteCode) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("enable", 1);
        queryWrapper.eq("deleted", 0);
        queryWrapper.ne("black_scope", 2);
        SyBlacklist syBlacklist = this.getOne(queryWrapper);
        if(!StringUtils.isEmpty(syBlacklist)){
            return true;
        }
        if(StringUtils.isEmpty(syBlacklist) && !StringUtils.isEmpty(superInviteCode)){
            QueryWrapper queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("me_invite_code",superInviteCode);
            queryWrapper1.eq("enable", 1);
            queryWrapper1.eq("deleted", 0);
            queryWrapper1.ne("black_scope", 1);
            SyBlacklist fuSyBlacklist = this.getOne(queryWrapper1);
            if(!StringUtils.isEmpty(fuSyBlacklist)){
                return true;
            }
        }
        return false;
    }

    @Override
    public ServerResponse saveSyBlacklist(SyBlacklist syBlacklist, UserVO authentication) {
        Integer blackScope = syBlacklist.getBlackScope();//1自己 2下级3 自己和下级
        Long userId = syBlacklist.getUserId();
        AppUser appUser = iAppUserService.selectAppUserByUserId(userId);
        SysLog sysLog = new SysLog();
        Administrator administrator = administratorService.getById(authentication.getUserId());
        sysLog.setUserId(authentication.getUserId());
        sysLog.setMethodExplain(administrator.getAdminitratorName()+"把用户"+appUser.getUserName()+"设置成了黑名单");
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(blackScope)) {
            sysLog.setResponseParams("设置失败：用户id/黑名单范围不能为空");
            return ServerResponse.createByErrorMessage("用户id/黑名单范围不能为空");
        }
        AppUser user = iAppUserService.selectAppUserByUserId(userId);
        if(StringUtils.isEmpty(user)){
            sysLog.setResponseParams("设置失败：用户不存在");
            return ServerResponse.createByErrorMessage("用户不存在");
        }
        if(blackScope == 1)
        sysLog.setMethodExplain(administrator.getAdminitratorName()+"把用户"+appUser.getUserName()+"设置成了黑名单");
        if(blackScope == 3)
        sysLog.setMethodExplain(administrator.getAdminitratorName()+"把用户"+appUser.getUserName()+"以及所有下级设置成了黑名单");
        //查询该用户是否是黑名单
        SyBlacklist oneSyBlacklist = getOneSyBlacklist(user.getUserId());
        boolean result;
        if(StringUtils.isEmpty(oneSyBlacklist)){//未加入过黑名单
            syBlacklist.setMeInviteCode(user.getMeInviteCode());
            syBlacklist.setSuperInviteCode(user.getSuperInviteCode());
             result = this.save(syBlacklist);
        }else{
            syBlacklist.setTableId(oneSyBlacklist.getTableId());
            syBlacklist.setEnable(1);
             result = this.updateById(syBlacklist);
        }
        if(result){
            sysLog.setResponseParams("成功");
            sysLogCommon.save(sysLog);
            return ServerResponse.createBySuccessMessage("操作成功");
        }
        sysLog.setResponseParams("设置失败");
        sysLogCommon.save(sysLog);
        return ServerResponse.createByErrorMessage("操作失败");
    }

    @Override
    public ServerResponse updateSyBlacklist(SyBlacklist syBlacklist,UserVO authentication) {
        AppUser user = iAppUserService.selectAppUserByUserId(syBlacklist.getUserId());
        if(StringUtils.isEmpty(user)){
            return ServerResponse.createBySuccessMessage("用户不存在");
        }
        SysLog sysLog = new SysLog();
        Administrator administrator = administratorService.getById(authentication.getUserId());
        sysLog.setUserId(authentication.getUserId());
        sysLog.setMethodExplain(administrator.getAdminitratorName()+"把用户"+user.getUserName()+"以及所有下級设置成了白名单");
        SyBlacklist oneSyBlacklist = getOneSyBlacklist(syBlacklist.getUserId());
        boolean result;
        if(StringUtils.isEmpty(oneSyBlacklist)){
            syBlacklist.setMeInviteCode(user.getMeInviteCode());
            syBlacklist.setSuperInviteCode(user.getSuperInviteCode());
            syBlacklist.setBlackReson("单独洗白用户");
            syBlacklist.setBlackScope(1);
            syBlacklist.setBlackType(1);
            syBlacklist.setEnable(0);
            result = this.save(syBlacklist);
        }else {
            SyBlacklist newSyBlacklist = new SyBlacklist();
            newSyBlacklist.setTableId(oneSyBlacklist.getTableId());
            newSyBlacklist.setEnable(0);
            result = this.updateById(newSyBlacklist);
        }
        if(result){
            sysLog.setResponseParams("成功");
            sysLogCommon.save(sysLog);
            return ServerResponse.createBySuccessMessage("操作成功");
        }
        sysLog.setResponseParams("设置失败");
        sysLogCommon.save(sysLog);
        return ServerResponse.createByErrorMessage("操作失败");
    }

    @Override
    public List<SyBlacklist> selectAllSyBlacklist() {
        return syBlacklistMapper.selectAllSyBlacklist();
    }

    @Override
    public Boolean verifyUserAgreement(Long userId) {
        long l = System.currentTimeMillis();
        QueryWrapper<SyBlacklist> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("enable",1);
        queryWrapper.eq("deleted",0);
        List<SyBlacklist> list = syBlacklistService.list(queryWrapper);
        if(CollectionUtils.isNotEmpty(list)){
            return true;
        }

        return false;
    }


    private SyBlacklist getOneSyBlacklist(Long userId){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id",userId);
        return this.getOne(queryWrapper);
    }


    private boolean addSubUser(AppUser user,SyBlacklist syBlacklist){
        //根据用户id查询该用户的所有下级
        QueryWrapper queryWrapper = new QueryWrapper();
        QueryWrapper newQueryWrapper = queryWrapper.select("user_id");
        newQueryWrapper.eq("super_invite_code",user.getMeInviteCode());
        List<AppUser> subUserList = iAppUserService.list(newQueryWrapper);
        List<SyBlacklist> syBlacklistlist = new ArrayList<>();
        for (AppUser appUser:subUserList){
            SyBlacklist newSyBlacklist = new SyBlacklist();
            newSyBlacklist.setUserId(appUser.getUserId());
            newSyBlacklist.setBlackType(syBlacklist.getBlackType());
            newSyBlacklist.setBlackScope(1);
            newSyBlacklist.setBlackReson("上级原因："+syBlacklist.getBlackReson());
            newSyBlacklist.setSuperInviteCode(user.getSuperInviteCode());
            newSyBlacklist.setMeInviteCode(appUser.getMeInviteCode());
            syBlacklistlist.add(newSyBlacklist);
        }
        return this.saveBatch(syBlacklistlist);
    }

    private boolean updateOne(AppUser user,Integer enable,Integer blackScope){
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.eq("super_invite_code",user.getSuperInviteCode());
        updateWrapper.set("enable",enable);
        if (blackScope != null)
        updateWrapper.set("black_scope",blackScope);
        updateWrapper.set("update_time",new Date());
        return this.update(updateWrapper);
    }
}
